using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Services.Discovery;
using Sports.App_Code.DB;

namespace wxConfig
{
    public class SdModelAccessToken
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
    }
    public class SdModelJsapiTicket
    {
        public int errcode { get; set; }
        public string errmsg { get; set; }
        public string ticket { get; set; }
        public int expires_in { get; set; }
    }
    public class SdModelAppIdTicket
    {
        public string appid { get; set; }
        public string ticket { get; set; }
    }
    public class SdModelWeiXinTicket
    {
        public string ticket { get; set; }
        public long second { get; set; }
    }
    public class SdModelSignature
    {
        public string appId { get; set; }
        public long timestamp { get; set; }
        public string nonceStr { get; set; }
        public string signature { get; set; }
        public string ticket { get; set; }
        public string str1 { get; set; }
    }
    public class SdModelLoginQrcode
    {
        public string scene { get; set; }
        public byte[] qrcode { get; set; }
    }
    public struct SdStructLogins
    {
        public int id { get; set; }
        public long ticks { get; set; }
    }
    public class SdModelLoginToken
    {
        public string token { get; set; }
        public SdModelUserInfo userinfo { get; set; }
    }
    public class Config
    {
        private string mAppid = "公众号appid";
        private string mSecret = "公众号secret";
        private long mNumber = 10000000;
        public Config()
        {

        }
        /// <summary>
        /// 获取唯一码
        /// </summary>
        /// <returns></returns>
        private string GetGuidString()
        {
            byte[] guid = Guid.NewGuid().ToByteArray();
            long i = 0;
            foreach (byte b in guid)
            {
                i *= ((int)b + 1);
            }
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }
        /// <summary>
        /// 获取小程序全局唯一后台接口调用凭据
        /// </summary>
        /// <returns></returns>
        private SdModelAccessToken getWeiXinAccessToken(string appid,string secret)
        {
            string url = String.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret);
            string content = this.httpGet(url);
            SdModelAccessToken token = DataToJson.FromJson<SdModelAccessToken>(content);
            if (!String.IsNullOrWhiteSpace(token.access_token))
            {
                return token;
            }
            return null;
        }
        /// <summary>
        /// 获取微信jsapi票据
        /// </summary>
        /// <returns></returns>
        public string GetWeiXinJsapiTicket()
        {
            //获取jsapi调用ticket，需要用公众号appid
            SdModelAccessToken smat = this.getWeiXinAccessToken(mAppid, mSecret);
            string url = String.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", smat.access_token);
            string content = this.httpGet(url);
            SdModelJsapiTicket smjt = DataToJson.FromJson<SdModelJsapiTicket>(content);
            if (!String.IsNullOrWhiteSpace(smjt.ticket))
            {
                SdModelWeiXinTicket wxTicket = new SdModelWeiXinTicket();
                wxTicket.ticket = smjt.ticket;
                wxTicket.second = DateTime.Now.Ticks / mNumber;
                //缓存ticket，微信调用次数有限制
                HttpContext.Current.Application.Lock();
                HttpContext.Current.Application["wxticket"] = wxTicket;
                HttpContext.Current.Application.UnLock();
                return smjt.ticket;
            }
            return "";
        }
        public string GetWeiXinAppidTicket()
        {

            SdModelAppIdTicket sdait = new SdModelAppIdTicket();
            sdait.ticket = this.GetWeiXinJsapiTicket();
            return DataToJson.ToJson<SdModelAppIdTicket>(sdait);
        }
        public string GetSignature(string url)
        {
            SdModelSignature sms = new SdModelSignature();
            sms.appId = "你的公众号appID";
            sms.timestamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds / 1000;
            sms.nonceStr = this.getNonceStr(16, true, true, true, false);
            //取缓存ticket
            Object oTicket = HttpContext.Current.Application.Get("wxticket");
            if (oTicket != null)
            {
                SdModelWeiXinTicket wxTicket = (SdModelWeiXinTicket)oTicket;
                if (DateTime.Now.Ticks / mNumber - wxTicket.second < 7198)
                {
                    sms.ticket = wxTicket.ticket;
                }
                else
                {
                    sms.ticket = this.GetWeiXinJsapiTicket();
                }
            }
            else
            {
                sms.ticket = this.GetWeiXinJsapiTicket();
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("jsapi_ticket=").Append(sms.ticket).Append("&noncestr=").Append(sms.nonceStr).Append("&timestamp=")
                .Append(sms.timestamp).Append("&url=").Append(url);
            sms.str1 = sb.ToString();
            string signature = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sb.ToString(), "SHA1");
            sms.signature = signature.ToLower();
            return DataToJson.ToJson<SdModelSignature>(sms);
        }

        /// <summary>
        /// HTTP Get数据获取
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private string httpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            using (WebResponse wr = request.GetResponse())
            {
                HttpWebResponse myResponse = (HttpWebResponse)wr;
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }
        /// <summary>
        /// 生成指定长度的随机码
        /// </summary>
        /// <param name="len"></param>
        /// <param name="useNum"></param>
        /// <param name="useLow"></param>
        /// <param name="useUpp"></param>
        /// <param name="useSpe"></param>
        /// <param name="custom"></param>
        /// <returns></returns>
        private string getNonceStr(int len, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom = "")
        {
            byte[] b = new byte[4];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
            Random r = new Random(BitConverter.ToInt32(b, 0));
            StringBuilder sb = new StringBuilder();
            string str = custom;
            if (useNum == true) { str += "0123456789"; }
            if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
            if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
            if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
            for (int i = 0; i < len; i++)
            {
                sb.Append(str.Substring(r.Next(0, str.Length - 1), 1));
            }
            return sb.ToString();
        }
    }
}